/**
 * Created by zlj on 2017/1/14.
 */
require("jquery");
var $form = require('js-path/formValideNotSub.js');
var $alert = require('libs/alert');
var $confirm = require('libs/confirm')
//修改模块名称临时变量
var $tempModualNameObject;
//添加模块位子临时变量
var $addObject;
$(function () {
    formValideInit();
    $("input[name=systemId]").on("change",function () {
        var systemId = $(this).val();
        $("#module-list .iteam").remove();
        getModule(systemId);
        getRoles(systemId);
    })
    var systemId = $("input[name=systemId]:checked").val();
    getModule(systemId);
    getRoles(systemId);
    $("#firstAdd").on("click",function () {
        var systemId = $("input[name=systemId]:checked").val();
        $("#module_form").find("input[name=systemId]").val(systemId)
    });
    //关闭时删除弹框内容
    $("#module1").on("hide.bs.modal",function () {
        $("#module_form").find("input[name!=roleIds]").val('');
    })

    $("#submit_form").on('click',function () {
        $("#module_form").submit();
    })
    
    //删除模块
    $("#module-list").on('click','button[name=delete]',function () {
            var $this = $(this);
            var id = $this.parent().find('input[name=id]').val();
           $confirm("确认删除此模块吗？如果模块为父模块将会删除其下全部子模块",function () {
               deleteOpt(id,$this);
           })
    });
    //上移
    $("#module-list").on('click','button[name=up]',function () {
        var $this = $(this);
        var $parent = $this.parent();
        var id = $parent.find('input[name=id]').val();
        var priority = $parent.find('input[name=priority]').val();
        if(priority != 0) {
            priority -- ;
        }
        updatePriority({id:id,priority:priority},$parent.parent().parent(),0);
    });
    //下移
    $("#module-list").on('click','button[name=down]',function () {
        var $this = $(this);
        var $parent = $this.parent();
        var id = $parent.find('input[name=id]').val();
        var priority = $parent.find('input[name=priority]').val();
        priority++;
        updatePriority({id:id,priority:priority},$parent.parent().parent(),1);
    });
    //二级菜单添加
    $("#module-list").on('click','button[name=add2]',function () {
        $addObject = $(this).parent().parent();
        var $parent = $addObject.parent();
        var parentId = $parent.find("input[name=id]:first").val();
        var parentName = $parent.find("span:first").html();
        $('#module_form').find('input[name=parentName]').val(parentName);
        $('#module_form').find('input[name=parent]').val(parentId);
        var systemId = $("input[name=systemId]:checked").val();
        $("#module_form").find("input[name=systemId]").val(systemId)
        $('#module1').modal('show');
    })
    //3级菜单添加
    $("#module-list").on('click','button[name=add3]',function () {
        $addObject = $(this).parent();
        var $parent = $addObject.parent().parent();
        var parentId = $parent.find("input[name=id]:first").val();
        var parentName = $parent.find("span:first").html();
        $('#module_form').find('input[name=parentName]').val(parentName);
        $('#module_form').find('input[name=parent]').val(parentId);
        var systemId = $("input[name=systemId]:checked").val();
        $("#module_form").find("input[name=systemId]").val(systemId)
        $('#module1').modal('show');
    })
    //修改菜单
    $("#module-list").on('click','button[name^=update]',function () {
         var $this = $(this);
        $tempModualNameObject = $this.parent().parent().parent();
        var id = $this.parent().find("input[name=id]").val();
        var parentName = '';
        if (this.name != 'update1') {
            parentName = $tempModualNameObject.parent().parent().find('span:first').html();
        }
        loadModual(id,parentName);
    })
})

function getModule(systemId) {
     $.ajax({
         url:'api/v1/p/mms/module/queryModules',
         type:'post',
         data:{systemId:systemId},
         dataType:'json',
         success:function (result) {
             if(result.code == 200){
                    load(result.data);
             }else{
                 $alert(result.message)
             }
         },
         error:function () {
             console.error("url:api/v1/p/mms/module/queryModules接口失败 ")
         }
     })
}

function load(data) {
      var divs = "";
    $.each(data,function (index,obj) {
        var div = "<div class='iteam'><h4><span>"+obj.moduleName+"</span><span class='btn-box'><input type='hidden' name='id' value='"+obj.id+"'/>" +
            "<input type='hidden' name='priority' value='"+obj.priority+"'/><button name='update1' class='btn btn-default'><i class='glyphicon glyphicon-pencil'>" +
            "</i>修改</button><button title='删除' class='btn btn-default' name='delete' ><i class='glyphicon glyphicon-trash'></i></button>" +
            "<button title='优先级上升' class='btn btn-default' name='up'><i class='glyphicon glyphicon-arrow-up'></i></button>" +
            "<button title='优先级下降' class='btn btn-default'  name='down'><i class='glyphicon glyphicon-arrow-down'></i></button></span></h4>";
        $.each(obj.childs,function (index,obj1) {
            div +="<div class='list row'><h5><span>"+obj1.moduleName+"</span><span class='btn-box'><input type='hidden' name='id' value='"+obj1.id+"'/>" +
                "<input type='hidden' name='priority' value='"+obj1.priority+"'/><button class='btn btn-default' name='update'>" +
                "<i class='glyphicon glyphicon-pencil'></i>修改</button><button class='btn btn-default' title='删除' name='delete'>" +
                "<i class='glyphicon glyphicon-trash'></i></button><button class='btn btn-default' title='优先级上升'  name='up'>" +
                "<i class='glyphicon glyphicon-arrow-up'></i></button><button class='btn btn-default' title='优先级下降' name='down'>" +
                "<i class='glyphicon glyphicon-arrow-down'></i></button></span></h5>";
            var divCheckBoxend ="<span class='iteam2'><button class='btn btn-default' name='add3'><i class='glyphicon glyphicon-plus'>" +
                    "</i>添加</button></span></div>";
            div+="<div class='checkbox col-xs-12'>";
            $.each(obj1.childs,function (index,obj2) {
                div+=" <span class='iteam2'><h6><span>"+obj2.moduleName+"</span><span class='btn-box'><input type='hidden' name='id' value='"+obj2.id+"'/>" +
                    "<input type='hidden' name='priority' value='"+obj2.priority+"'/><button class='btn btn-default'name='update' >" +
                    "<i class='glyphicon glyphicon-pencil'></i>修改</button><button class='btn btn-default' title='删除' name='delete'>" +
                    "<i class='glyphicon glyphicon-trash'></i></button></span></h6></span>";
            })
            div += divCheckBoxend+"</div>";
        })
        div+="<div class='list row'><h5><button class='btn btn-default'  name='add2'><i class='glyphicon glyphicon-plus'>" +
            "</i>添加</button></h5></div></div>";
        divs+=div;
    })
    $("#module-list").append(divs);
}

function formValideInit() {
    $form({selector:"#module_form"},{
        moduleName:{required:true},moduleDesc:{required:true},moduleType:{required:true},
        priority:{required:true,digits:true}},{
        moduleName:{required:'模块名称不能为空'},moduleDesc:{required:'模块描述不能为空'},moduleType:{required:'模块类型不能为空'},
        priority:{required:'模块优先级不能为空',digits:'模块优先级必须为数字'}}
        ,function () {
           var data  = $('#module_form').serializeObject();
            if(data.roleIds){
                if(!data.roleIds.push){ //判断roleIds是否为数组
                    data.roleIds = [data.roleIds];
                }
            }

           var type = data.id == '' ? 0:1;
           addOrUpdateOpt(data,type);
        })
}

/*
*  添加或更新操作
*   type 0 add  1 update
*/
function addOrUpdateOpt(data,type) {
    var url = 'api/v1/p/mms/module/create';
    if(1 === type){
        url = 'api/v1/p/mms/module/update'
    }
    $.ajax({
        url: url,
        type:'post',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        success:function (result) {
            if(result.code == 200){
                var obj =  0 === type ? result.data : data
                addOrUpdateModual(obj,type);
                $('#module1').modal('hide');
            }else{
                $alert(result.message);
            }
        },
        error:function () {
            console.error("接口："+url+" 调用失败");
        }
    })
}

/**
 *  添加或修改Modual 暂时不提供优先级顺序显示
 *  type 0 add 1 update
 */
function addOrUpdateModual(data,type) {
    if(0 === type){
        if($addObject == undefined){
            addFirstModual(data,$('#module-list .iteam:last'));
        }else if($addObject[0].tagName == 'DIV') {
            addTwoModual(data,$addObject);
        }else {
            addThreeModual(data,$addObject);
        }
        $addObject = undefined;
    }else if(1 === type){
        $tempModualNameObject.find('span:first').html(data.moduleName);
        $tempModualNameObject.find('input[name=priority]').html(data.priority);
        moveUp($tempModualNameObject,data.priority,0);
        moveUp($tempModualNameObject,data.priority,1);
    }
}
/**
 * 添加一级菜单
 */
function addFirstModual(obj,$obj) {
     var div = "<div class='iteam'><h4><span>"+obj.moduleName+"</span><span class='btn-box'><input type='hidden' name='id' value='"+obj.id+"'/>" +
         "<input type='hidden' name='priority' value='"+obj.priority+"'/><button name='update' class='btn btn-default'><i class='glyphicon glyphicon-pencil'>" +
         "</i>修改</button><button title='删除' class='btn btn-default' name='delete' ><i class='glyphicon glyphicon-trash'></i></button>" +
         "<button title='优先级上升' class='btn btn-default' name='up'><i class='glyphicon glyphicon-arrow-up'></i></button>" +
         "<button title='优先级下降' class='btn btn-default'  name='down'><i class='glyphicon glyphicon-arrow-down'></i></button></span></h4><div class='list row'>" +
         "<h5><button class='btn btn-default'  name='add'><i class='glyphicon glyphicon-plus'>" +
         "</i>添加</button></h5></div></div>";
    $obj.after(div);
    moveUp($obj.next(),obj.priority,0);
}
/**
 * 添加二级菜单
 */
function addTwoModual(obj,$obj) {
   var div = '<div class="list row"><h5><span>'+obj.moduleName+'</span><span class="btn-box"><input type="hidden" name="id"' +
       ' value="'+obj.id+'"><input type="hidden" name="priority" value="'+obj.priority+'"><button class="btn btn-default" name="update">' +
       '<i class="glyphicon glyphicon-pencil"></i>修改</button><button class="btn btn-default" title="删除" name="delete">' +
       '<i class="glyphicon glyphicon-trash"></i></button><button class="btn btn-default" title="优先级上升" name="up">' +
       '<i class="glyphicon glyphicon-arrow-up"></i></button><button class="btn btn-default" title="优先级下降" name="down">' +
       '<i class="glyphicon glyphicon-arrow-down"></i></button></span></h5><div class="checkbox col-xs-12"><span class="iteam2">' +
       '<button class="btn btn-default" name="add3"><i class="glyphicon glyphicon-plus"></i>添加</button></span></div></div>';
    $obj.before(div);
    moveUp($obj.prev(),obj.priority,0);
}

function addThreeModual(obj,$obj) {
    var div =" <span class='iteam2'><h6><span>"+obj.moduleName+"</span><span class='btn-box'><input type='hidden' name='id' value='"+obj.id+"'/>" +
        "<input type='hidden' name='priority' value='"+obj.priority+"'/><button class='btn btn-default'name='update' >" +
        "<i class='glyphicon glyphicon-pencil'></i>修改</button><button class='btn btn-default' title='删除' name='delete'>" +
        "<i class='glyphicon glyphicon-trash'></i></button></span></h6></span>";
    $obj.before(div);
    moveUp($obj.prev(),obj.priority,0);
}

function deleteOpt(id,$clickObj) {
   $.ajax({
       url:'api/v1/p/mms/module/delete',
       type:'post',
       data:{
           id:id
       },
       dataType:'json',
       success:function (result) {
            if(result.code == 200){
                $clickObj.parent().parent().parent().remove();
            }else {
                $alert(result.message);
            }
       },
       error:function () {
           console.error('url: api/v1/p/mms/module/delete 接口错误');
       }
   })
}

//模块优先级修改 type: 0-上移 1-下移
function updatePriority(data,$moveObj,type) {
    $.ajax({
        url:'api/v1/p/mms/module/updatePriority',
        type:'post',
        data:JSON.stringify(data),
        contentType:'application/json;charset=utf-8',
        dataType:'json',
        success:function (result) {
            if(result.code ==  200) {
                $moveObj.find('input[name=priority]:first').val(data.priority);
                  moveUp($moveObj,data.priority,type);
            }else {
                $alert(result.message);
            }
        },
        error:function () {
            console.error('url:api/v1/p/mms/module/updatePriority ')
        }
    })
}

// 递归移动元素
function moveUp($moveObj,priority,type) {
    if(0 === type) {
        var $upObj = $moveObj.prev();
        if($upObj[0].tagName != $moveObj[0].tagName) {
            return false;
        }
        var uPriority = $upObj.find('input[name=priority]:first').val();
        if( uPriority > priority) {
            $upObj.before($moveObj);
            moveUp($moveObj,priority,type);
        }
    }else if(1 === type ) {
        var $downObj = $moveObj.next();
        var dPriority = $downObj.find('input[name=priority]:first').val();
        if(dPriority < priority) {
            $downObj.after($moveObj);
            moveUp($moveObj,priority,type);
        }
    }
}
//load modual
function loadModual(id,parentName) {
    $.ajax({
        url:'api/v1/p/mms/module/detail',
        type:'post',
        data:{
            id:id
        },
        dataType:'json',
        success:function (result) {
            if (result.code == 200) {
               var $mForm = $('#module_form');
                $mForm.setForm(result.data);
               $mForm.find('input[name=parentName]').val(parentName);
                $('#module1').modal("show");
            }else {
                $alert(result.message);
            }
        },
        error:function () {
            console.error('url:api/v1/p/mms/module/detail 调用接口无效');
        }
    })
}

function getRoles(systemId) {
    $.ajax({
        url:'api/v1/p/mms/authRole/querySimpleRole',
        type:'post',
        data:{
            systemId:systemId
        },
        success:function (result) {
             if(result.code == 200 ) {
                 $('#module_form div[name=role_error]').empty();
                 appendRoles(result.data);
             } else {
                  var pStr =  "<p  class='error'>"+result.message+"</p>"
                 $('#module_form div[name=role_error]').empty().append(pStr);
             }
        },
        error:function () {
            console.error('接口：api/v1/p/mms/authRole/querySimpleRole 调用失败 ')
        }
    })
}

function appendRoles(data) {
    var checkBoxs = '';
    $.each(data,function (index,obj) {
        checkBoxs += '<label class="col-xs-4"><input name="roleIds" type="checkbox" value="'+obj.id+'"> '+
            obj.name+'</label>';
    });
    $('#module_form').find('div.checkbox').empty().append(checkBoxs);
}

